package com.alog.javaee.day39;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @Auther: Ye Zhengdong
 * @Date: 2019/2/20 18:52
 * @Description:
 */
@WebServlet("/loginServlet2")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String checkCode = req.getParameter("checkCode");

        String sessionCheckCode = (String) req.getSession().getAttribute("sessionCheckCode");
        req.getSession().removeAttribute("sessionCheckCode");

        if(sessionCheckCode != null && !sessionCheckCode.equalsIgnoreCase(checkCode)){
            req.setAttribute("cc_error", "验证码错误");
            req.getRequestDispatcher("/login.jsp").forward(req, resp);
            return;
        }
        if("zhangsan".equals(username) && "123".equals(password)){
            req.getSession().setAttribute("user", username);
            resp.sendRedirect(req.getContextPath() + "/success.jsp");
        } else {
            req.setAttribute("login_error", "用户名或密码错误");
            req.getRequestDispatcher("/login.jsp").forward(req, resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
